<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2005/08/07 05:20:29 $)
// $RCSfile: functions_privatemessages.php,v $ : $Revision: 1.3 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

// ======= MESSAGE TYPES =======
define("PRVMSG_RECEIVED", 1);
define("PRVMSG_SENT", 2);

// ======= MESSAGE STATUS =======
define("PRVMSG_UNREAD", 1);
define("PRVMSG_READ", 2);

/**
* Delete the given private messages
*/
function deletePrivateMessages($privatemessageidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($privatemessageidlist))
	{
		return false;
	}

	// Verify that the messages we are deleting are owned by this staff
	$finalprivatemessageidlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."privatemessages` WHERE `privatemessageid` IN (". buildIN($privatemessageidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (($dbCore->Record["tostaffid"] == $_SWIFT["staff"]["staffid"] && $dbCore->Record["msgtype"] == PRVMSG_RECEIVED) || ($dbCore->Record["fromstaffid"] == $_SWIFT["staff"]["staffid"] && $dbCore->Record["msgtype"] == PRVMSG_SENT))
		{
			$finalprivatemessageidlist[] = $dbCore->Record["privatemessageid"];
		}
	}

	if (!count($finalprivatemessageidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."privatemessages` WHERE `privatemessageid` IN (". buildIN($finalprivatemessageidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."privatemessagedata` WHERE `privatemessageid` IN (". buildIN($finalprivatemessageidlist) .");");

	rebuildPrivateMessageCache($_SWIFT["staff"]["staffid"]);

	return true;
}

/**
* Update the read status for given private messages
*/
function updateMessageReadStatus($privatemessageidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($privatemessageidlist))
	{
		return false;
	}

	// Verify that the messages we are changing status for are owned by this staff
	$finalprivatemessageidlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."privatemessages` WHERE `privatemessageid` IN (". buildIN($privatemessageidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (($dbCore->Record["tostaffid"] == $_SWIFT["staff"]["staffid"] && $dbCore->Record["msgtype"] == PRVMSG_RECEIVED) || ($dbCore->Record["fromstaffid"] == $_SWIFT["staff"]["staffid"] && $dbCore->Record["msgtype"] == PRVMSG_SENT))
		{
			$finalprivatemessageidlist[] = $dbCore->Record["privatemessageid"];
		}
	}

	if (!count($finalprivatemessageidlist))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."privatemessages` SET `msgstatus` = '". PRVMSG_READ ."' AND `readdate` = '". DATENOW ."' WHERE `privatemessageid` IN (". buildIN($finalprivatemessageidlist) .");");

	rebuildPrivateMessageCache($_SWIFT["staff"]["staffid"]);
}

/**
* Checks for permission on given private message and retrieves it, if permission isnt valid, returns false..
*/
function getPrivateMessage($privatemessageid)
{
	global $dbCore, $_SWIFT;

	$_privatemessage = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."privatemessages` AS privatemessages LEFT JOIN `". TABLE_PREFIX ."privatemessagedata` AS privatemessagedata ON (privatemessages.privatemessageid = privatemessagedata.privatemessageid) WHERE privatemessages.privatemessageid = '". intval($privatemessageid) ."';");
	if (($_privatemessage["tostaffid"] == $_SWIFT["staff"]["staffid"] && $_privatemessage["msgtype"] == PRVMSG_RECEIVED) || ($_privatemessage["fromstaffid"] == $_SWIFT["staff"]["staffid"] && $_privatemessage["msgtype"] == PRVMSG_SENT))
	{
		return $_privatemessage;
	}

	return false;	
}

/**
* Send a new private message to staff members
*/
function sendPrivateMessage($tostaffidlist, $subject, $contents)
{
	global $dbCore, $_SWIFT, $template;

	if (!_is_array($tostaffidlist))
	{
		return false;
	}

	foreach ($tostaffidlist as $key=>$val)
	{
		$_prvmsgsql[] = "('". intval($_SWIFT["staff"]["staffid"]) ."', '". intval($val) ."', '". $dbCore->escape($subject) ."', '". DATENOW ."', '". PRVMSG_RECEIVED ."', '". PRVMSG_UNREAD ."', '0')";
		$_prvmsgsql[] = "('". intval($_SWIFT["staff"]["staffid"]) ."', '". intval($val) ."', '". $dbCore->escape($subject) ."', '". DATENOW ."', '". PRVMSG_SENT ."', '". PRVMSG_READ ."', '". DATENOW ."')";
	}

	if (!count($_prvmsgsql))
	{
		return false;
	}

	// Insert all private messages
	$privatemessageidlist = array();
	foreach ($_prvmsgsql as $key=>$val)
	{
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."privatemessages` (`fromstaffid`, `tostaffid`, `subject`, `dateline`, `msgtype`, `msgstatus`, `readdate`) VALUES ". $val.";");
		$privatemessageid = $dbCore->lastInsertId();
		$privatemessageidlist[] = $privatemessageid;
	}

	// Ok now insert all the private message data
	$_datasql = array();
	foreach ($privatemessageidlist as $key=>$val)
	{
		$_datasql[] = "('". intval($val) ."', '". $dbCore->escape($contents) ."')";
	}

	if (!count($_datasql))
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."privatemessagedata` (`privatemessageid`, `contents`) VALUES ".implode(",", $_datasql).";");

	// Rebuild the staff caches
	foreach ($tostaffidlist as $key=>$val)
	{
		rebuildPrivateMessageCache($val);
	}

	// We now send the required email alerts..
	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	// Set to master group
	$template->setGroup(1);
	$template->assign("fromstaff", $_SWIFT["staff"]["fullname"]);
	$template->assign("prvsubject", $subject);
	$template->assign("contentshtml", getProcessedHTML($contents));
	$template->assign("contentstext", getProcessedText($contents));

	$template->assign("ishtml", false);
	$emailtext = $template->displayTemplate("staffpmalert", TEMPLATE_DB);
	$template->assign("ishtml", true);
	$emailhtml = $template->displayTemplate("staffpmalert", TEMPLATE_DB);
		
	$mailObj->setSubject($_SWIFT["language"]["emailalertsubject"]);
	$mailObj->setData($emailhtml, $emailtext);
	$mailcount = 0;
	$emaillist = array();
	
	$dbCore->query("SELECT `staffid`, `email`, `fullname`, `enablepmalerts` FROM `". TABLE_PREFIX ."staff` WHERE `staffid` IN (". buildIN($tostaffidlist) .");");
	while ($dbCore->nextRecord())
	{
		if ($dbCore->Record["enablepmalerts"] == 1)
		{
			$emaillist[] = $dbCore->Record["email"];
			$mailcount++;
		}
	}

	$mailObj->sendMail($emaillist, $_SWIFT["staff"]["email"], $_SWIFT["staff"]["fullname"], true);

	return true;
}

/**
* Rebuilds the staff private message cache in staff table
*/
function rebuildPrivateMessageCache($staffid)
{
	global $dbCore, $_SWIFT;

	$_msgstatus = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."privatemessages` WHERE `tostaffid` = '". intval($staffid) ."' AND `msgtype` = '". PRVMSG_RECEIVED ."' AND msgstatus = '". PRVMSG_UNREAD ."';");
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."staff` SET `pmunread` = '". intval($_msgstatus["totalitems"]) ."' WHERE `staffid` = '". intval($staffid) ."';");

	return true;
}

/**
* Adds > in front of message lines
*/
function convertMessageToQuote($messagedata)
{
	$messagedata = preg_replace("#(\r\n|\r|\n)#s", SWIFT_CRLF, $messagedata);
	$msgarray = explode(SWIFT_CRLF, $messagedata);
	
	$finalmessage = "";
	foreach ($msgarray as $key=>$val)
	{
		$finalmessage .= " > ".$val.SWIFT_CRLF;
	}

	return $finalmessage;
}

?>